package com.itheima.dao.Impl;

import com.itheima.dao.RoleDao;
import com.itheima.domain.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("roleDao")
public class RoleDaoImpl implements RoleDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //查询所有角色
    @Override
    public List<Role> findAll(){
        return jdbcTemplate.query("select * from sys_role where 1=1", new BeanPropertyRowMapper<Role>(Role.class));
    }

//    根据用户id查找对应所有的角色列表
    @Override
    public List<Role> findRoleByUserId(long id){
        List<Role> roleList = jdbcTemplate.query("SELECT * FROM sys_role r,sys_user_role ur WHERE ur.userId=? AND ur.roleID=r.id", new BeanPropertyRowMapper<Role>(Role.class), id);
        return roleList;
    }

    @Override
    public void delUserRoleRel(Long roleId) {
        jdbcTemplate.update("delete from sys_user_role where roleId=?",roleId);
    }

    @Override
    public void del(Long roleId) {
        jdbcTemplate.update("delete from sys_role where id=?",roleId);
    }

    //新建一个角色

    @Override
    public boolean save(Role role) {
        String sql="insert into sys_role values (?,?,?)";
        int row = jdbcTemplate.update(sql, null, role.getRoleName(), role.getRoleDesc());
        if (row !=0){
            return true;
        }
        return false;
    }
}
